﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FaWorks.WebSite.Models;

namespace FaWorks.WebSite.Controllers.Manager
{
    public class SiteMapController : Controller
    {
        private FaDataBase db = new FaDataBase();

        public ActionResult Index()
        {
            var list = db.SitemapItems.ToList();
            list.Sort(new SitemapItemCompare<SitemapItem>());
            return View(list);
        }

        private void SortChild(SitemapItem item) {
            if (item != null)
            {
                item.Childs.Sort(new SitemapItemCompare<SitemapItem>());
                item.Childs.ForEach(m => SortChild(m));
            }
        }

        public ActionResult GetJson(string name)
        {
            SitemapItem sitemapitem = db.SitemapItems
                .Include<SitemapItem>("Childs.Childs.Childs.Childs.Childs.Childs.Childs.Childs.Childs")
                .FirstOrDefault<SitemapItem>(m => m.Location == name);
            if (sitemapitem == null)
            {
                return HttpNotFound();
            }

            SortChild(sitemapitem);

            return Json(sitemapitem, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Create(Guid? pid,SitemapItem sitemapitem)
        {
            if (ModelState.IsValid)
            {
                sitemapitem.ID = Guid.NewGuid();
                if (pid != null)
                {
                    var psitemapitem = db.SitemapItems.Find(pid);
                    psitemapitem.AddChild(sitemapitem);
                }
                else
                {
                    db.SitemapItems.Add(sitemapitem);
                }
                db.SaveChanges();
            }

            return Json(sitemapitem);
        }

        [HttpGet]
        public ActionResult Edit(Guid id)
        {
            var sitemapitem = db.SitemapItems.Find(id);
            return Json(sitemapitem, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Edit(SitemapItem sitemapitem)
        {
            if (ModelState.IsValid)
            {
                db.Entry(sitemapitem).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(sitemapitem);
        }

        [HttpPost]
        public ActionResult Delete(Guid id)
        {
            SitemapItem sitemapitem = db.SitemapItems.Find(id);
            db.SitemapItems.Remove(sitemapitem);
            db.SaveChanges();
            return Json(sitemapitem);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}